import axios from "axios";
import { Message, Loading } from "element-ui";
import store from "../store";
import { getToken } from "./auth"; //获取到token
import { dateFormat } from "./index";
import md5 from "js-md5";

function isNumber(obj) {
  return typeof obj === "number" && !isNaN(obj);
}

function isString(str) {
  return typeof str == "string" && str.constructor == String;
}

//创建一个axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 300000,
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const secretKey = "sdksdksdcfsd";
    const timeStamp = new Date().getTime() + "";
    let crypt = "";
    if (config.method === "get") {
      config.params = config.params ? config.params : { timeStamp };
      for (let key in config.params) {
        config.params[key] =
          config.params[key] || config.params[key] === 0
            ? isNumber(config.params[key])
              ? config.params[key] + ""
              : config.params[key]
            : "";
        if (isString(config.params[key])) {
          config.params[key] = config.params[key].trim();
        }
      }
      crypt = md5(JSON.stringify(config.params) + secretKey);
    } else {
      if (config.url === "/Admin/upload") {
        config.data.append("timeStamp", timeStamp);
        const params = {
          sizeLimit: config.data.get("sizeLimit"),
          riginalName: config.data.get("riginalName"),
          timeStamp,
        };
        crypt = md5(JSON.stringify({ ...params }) + secretKey);
      } else {
        config.data =
          config.data && JSON.stringify(config.data) !== "{}"
            ? config.data
            : { timeStamp };
        for (let key in config.data) {
          config.data[key] =
            config.data[key] || config.data[key] === 0
              ? isNumber(config.data[key])
                ? config.data[key] + ""
                : config.data[key]
              : "";
          if (isString(config.data[key])) {
            config.data[key] = config.data[key].trim();
          }
        }
        crypt = md5(JSON.stringify(config.data) + secretKey);
      }
    }
    config.headers["adminCrypt"] = crypt;
    let token = getToken(); //获取token
    if (token) {
      //每次请求都需要带上token去请求接口
      config.headers["Authorization"] = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//响应拦截器
service.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      if (response.data.status === 200) {
        return Promise.resolve(response.data);
      } else {
        Message.error(response.data.msg);
        if (response.data.status === 300) {
          store.dispatch("user/logout");
        }
        return Promise.reject(response);
      }
    } else {
      return Promise.reject(response);
    }
  },
  (error) => {
    switch (error.response.status) {
      case 405:
        Message.error(error.response.info);
        break;
      default:
        break;
    }
    return Promise.reject(error);
  }
);

export default {
  /**
   * get方法，对应get请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   * @param {Boolean} flag [是否弹出提示]
   */
  get(url, params, flag) {
    return new Promise((resolve, reject) => {
      service
        .get(url, {
          params: params,
        })
        .then((res) => {
          if (flag && res.status === 200&&res.msg != "获取成功") {
            Message.success(res.msg);
          }
          resolve(res.data);
        })
        .catch((err) => {
          reject(err.data);
        });
    });
  },

  /**
   * post方法，对应post请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   * @param {Boolean} flag [是否弹出提示]
   */
  post(url, params, flag) {
    return new Promise((resolve, reject) => {
      service
        .post(url, params)
        .then((res) => {
          if (flag && res.status === 200&&res.msg != "获取成功") {
            Message.success(res.msg);
          }
          resolve(res.data);
        })
        .catch((err) => {
			console.log(err)
          reject(err.data);
        });
    });
  },
  /**
   * upload方法，对应upload post请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   * @param {Boolean} flag [是否弹出提示]
   */
  upload(url, params, flag) {
    return new Promise((resolve, reject) => {
      service
        .post(url, params, {
          headers: { "Content-Type": "multipart/form-data" },
        })
        .then((res) => {
          if (flag && res.status === 200) {
            Message.success(res.msg);
          }
          resolve(res.data);
        })
        .catch((err) => {
          reject(err.data);
        });
    });
  },
  /**
   * export方法
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   */
  export(url, params, name) {
    const loading = Loading.service({
      lock: true,
      text: "导出中。。。。。。",
      spinner: "el-icon-loading",
    });
    return new Promise((resolve, reject) => {
      const secretKey = "sdksdksdcfsd";
      const timeStamp = new Date().getTime() + "";
      const data =
        params && JSON.stringify(params) !== "{}" ? params : { timeStamp };
      for (let key in data) {
        data[key] =
          data[key] || data[key] === 0
            ? isNumber(data[key])
              ? data[key] + ""
              : data[key]
            : "";
        if (isString(data[key])) {
          data[key] = data[key].trim();
        }
      }
      const crypt = md5(JSON.stringify(data) + secretKey);
      axios
        .post(process.env.VUE_APP_BASE_API + url, data, {
          responseType: "blob",
          headers: {
            "Content-Type": "application/json",
            Authorization: getToken(),
            adminCrypt: crypt,
          },
        })
        .then((res) => {
          const link = document.createElement("a");
          let blob = new Blob([res.data], {
            type: "application/vnd.ms-excel",
          });
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          link.download = name + dateFormat(new Date()) + ".xls";
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          loading.close();
          resolve(true);
        })
        .catch((err) => {
          loading.close();
          reject(err);
        });
    });
  },
};
